// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ws_contact

import (
	"context"
	"errors"
)

// Hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
	// Registered clients.
	clients map[string]*Client

	// Inbound messages from the clients.
	//broadcast chan []byte

	// Register requests from the clients.
	register chan *Client

	// Unregister requests from clients.
	unregister chan *Client
}

func NewHub() *Hub {
	return &Hub{
		//broadcast:  make(chan []byte),
		register:   make(chan *Client),
		unregister: make(chan *Client),
		clients:    make(map[string]*Client),
	}
}
func (h *Hub) Write(nodeId string, data []byte) error {
	if client, ok := h.clients[nodeId]; ok {
		client.send <- data
		return nil
	}
	return errors.New("nodeId not found")
}
func (h *Hub) Run(ctx context.Context) {
	for {
		select {
		case <-ctx.Done():
			return
		case client := <-h.register:
			h.clients[client.nodeId] = client
		case client := <-h.unregister:
			if _, ok := h.clients[client.nodeId]; ok {
				delete(h.clients, client.nodeId)
				close(client.send)
			}
		}
	}
}
